'''
Description: experiment runing tools
    hello:
        say hello world
    clear:
        当config.json 中 存在section CLEAR时,执行对应的匹配方式
Author: 
LastEditors: M
'''
import os
_cur_dir = os.getcwd()
_file_path = os.path.abspath(__file__)
_piker_dir = os.path.dirname(_file_path)
_piker_pdir = os.path.dirname(_piker_dir)
if _cur_dir!=_piker_pdir:
    print(f"ERROR:execute `manage` in a wrong position change current dir to\033[1;31m\n\t{_piker_pdir}\033[0m")
    exit(-1)
import shutil
import argparse
from compoments.config import PROJECT_DIR
import compoments.utils as U
from compoments.params import load_params
from compoments.utils import errormsg
import compoments.config as CFG

def _clear():
    """
    """
    pass
def _get_sys_info():
    from compoments.manage_process import assign_task
    assign_task()
    pass
def _gen():
    from compoments.gen_group_config import ConfigBuilder
    cb = ConfigBuilder()
    cb.run()
    
def _collect_output():
    from compoments.utils import get_root_path
    to_dir = get_root_path(CFG.artwork_dir)

    for d in [to_dir]:
        if not os.path.exists(d):
            os.makedirs(d)    
    #todo 临时策略
    collect_cmd = CFG.clear_cmds
    cd = os.getcwd()
    os.chdir(get_root_path(CFG.root_dir))
    for c in collect_cmd:
        os.system(c)
    os.chdir(cd)
        
def _run():
    """
    先实现 非并行版本
    """
    from compoments.settings import load_setting
    from compoments.task import PikerTask,T_task
    from compoments.manage_process import TaskCollection,assign_task
    # backup
    
    exp_cfg_fp = os.path.join(CFG.PIKER_DIR,CFG.exp_config)
    exp_cfg_fp_bak = os.path.join(
        os.path.dirname(exp_cfg_fp),
        "bak."+os.path.basename(exp_cfg_fp)
    )
    
    if os.path.exists(exp_cfg_fp):
        shutil.move(exp_cfg_fp,exp_cfg_fp_bak)
    old_cd = os.getcwd()
    chdir_flag = False
    if old_cd!=CFG.PROJECT_DIR:
        os.chdir(PROJECT_DIR)
        chdir_flag = True

    if chdir_flag:
        os.chdir(CFG.PROJECT_DIR)
    if os.path.exists(exp_cfg_fp_bak):
        shutil.move(exp_cfg_fp_bak,exp_cfg_fp)

    st = load_setting(os.path.join(CFG.PIKER_DIR,CFG.setting_file))

    cts = TaskCollection()    
    for i in range(len(st)):
        try:            
            exp = st.iloc[i]
            if exp['state']!=0:
                print(U._ok_("skip"),exp['id'])
                continue
            cur_params_path = os.path.join(CFG.PROJECT_DIR,exp['save_dir'],exp['name'])
            if not os.path.exists(cur_params_path):
                errormsg("生成的参数文件不存在,请先生成",emphasis=cur_params_path)
                exit(-1)
            cts.append_task(PikerTask(exp['id'],exp_cfg_fp,cur_params_path))
            # cts.append_task(T_task())

        except Exception as e:
            errormsg("运行任务遇到错误",emphasis=f"{U._warning_(str(exp))}\n\t{str(e)}")
            exit(-1)
    assign_task(cts)

def _test():
    """
    使用python执行任务
    """
    P= load_params()
    exe_key = CFG.exe_command_key
    if exe_key not in P:
        errormsg(f"命令没找到,在{CFG.exp_config}中创建{U._emphasis_(exe_key)}")
        exit(-1)
    print(f"excute {U._warning_(P[exe_key])}@{U._primary_(CFG.PROJECT_DIR)}")
    s = os.system(P[exe_key])
    if s==0:
        print(U._ok_("running success"))
    else:
        errormsg("返回 code",emphasis=str(s))
def _info():
    """
    获取当前的项目信息
    """
    from compoments.info import show_info
    show_info()

_REG_FUN = (
    "clear",
    "run",
    "gen",
    "info",
    "test",
    "get_sys_info",
)
if __name__ == "__main__":
    argv = argparse.ArgumentParser(
        prog="python manage.py",
        description="""experiment runing tools""",
    )
    argv.add_argument("-f","--fun",
        type=str,
        required=True,
        #default="run",
        choices=_REG_FUN )
        
    arg = argv.parse_args()
    fun = "_"+arg.fun
    #test
    if fun in locals():
        locals()[fun]()
    